<template>
  <div class="modern-user-manage">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <div class="title-icon">
            <el-icon :size="24" color="#667eea">
              <UserFilled />
            </el-icon>
          </div>
          <div class="title-info">
            <h1 class="page-title">用户管理</h1>
            <p class="page-subtitle">管理系统中的所有用户信息</p>
          </div>
        </div>

        <div class="header-actions">
          <el-button type="primary" @click="addDialogVisible = true">
            <el-icon><Plus /></el-icon>
            <span>添加用户</span>
          </el-button>
          <el-button @click="exportUsers">
            <el-icon><Download /></el-icon>
            <span>导出数据</span>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <div class="stats-grid">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ totalUsers }}</div>
            <div class="stat-label">总用户数</div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ activeUsers }}</div>
            <div class="stat-label">活跃用户</div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ verifiedUsers }}</div>
            <div class="stat-label">已认证用户</div>
          </div>
        </el-card>

        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ bannedUsers }}</div>
            <div class="stat-label">被禁用户</div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <el-card class="search-card" shadow="never">
        <el-form :inline="true" :model="searchForm" @submit.prevent>
          <el-form-item label="用户名">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable
            />
          </el-form-item>

          <el-form-item label="手机号">
            <el-input
              v-model="searchForm.phone"
              placeholder="请输入手机号"
              clearable
            />
          </el-form-item>

          <el-form-item label="角色状态">
            <el-select
              v-model="searchForm.roleId"
              placeholder="全部角色"
              clearable
            >
              <el-option label="全部角色" :value="''" />
              <el-option label="普通用户" :value="1" />
              <el-option label="已认证" :value="2" />
              <el-option label="被拒绝" :value="3" />
              <el-option label="封禁用户" :value="-1" />
              <el-option label="待审核" :value="0" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <el-card class="table-card" shadow="never">
        <div class="table-header">
          <h3>用户列表 (共 {{ total }} 条记录)</h3>
          <el-button @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>

        <el-table
          :data="userList"
          v-loading="loading"
          stripe
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />

          <el-table-column prop="headPic" label="头像" width="100" align="center">
            <template #default="scope">
              <el-image
                v-if="scope.row.headPic"
                :src="getHeadPicUrl(scope.row.headPic)"
                style="width:48px;height:48px;border-radius:50%;object-fit:cover;"
                fit="cover"
              />
              <span v-else style="color:#ccc;">无</span>
            </template>
          </el-table-column>

          <el-table-column prop="username" label="用户名" min-width="120" align="center" />
          <el-table-column prop="phone" label="手机号" min-width="140" align="center" />

          <el-table-column prop="roleId" label="角色" min-width="100" align="center">
            <template #default="scope">
              <el-tag :type="getRoleTagType(scope.row.roleId)" size="small">
                {{ getRoleText(scope.row.roleId) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="320" align="center">
            <template #default="scope">
              <el-button size="small" type="primary" @click="editUser(scope.row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-button
                v-if="scope.row.roleId !== -1"
                size="small"
                type="danger"
                @click="banUserHandler(scope.row.id)"
              >
                封禁
              </el-button>
              <el-button
                v-else
                size="small"
                type="success"
                @click="unbanUserHandler(scope.row.id)"
              >
                解封
              </el-button>
              <el-button
                v-if="scope.row.roleId === 0"
                size="small"
                type="warning"
                @click="openAuditDialog(scope.row)"
              >
                审核
              </el-button>
              <el-popconfirm
                title="确定删除该用户吗？"
                @confirm="deleteUserHandler(scope.row.id)"
              >
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="pageNum"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        class="pagination"
      />
      <!-- 编辑用户对话框 -->
      <el-dialog v-model="editDialogVisible" title="编辑用户" width="400px" class="custom-dialog" :close-on-click-modal="false">
        <el-form :model="editForm" ref="editFormRef" label-width="80px" :rules="rules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="editForm.phone" />
          </el-form-item>
          <el-form-item label="头像">
            <el-upload
              class="upload-demo"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleEditFileChange"
            >
              <el-button type="primary">选择头像</el-button>
            </el-upload>
            <div v-if="editForm.headPicUrl || editForm.headPic" class="preview-img">
              <img :src="isBase64(editForm.headPicUrl) ? editForm.headPicUrl : getHeadPicUrl(editForm.headPicUrl ? editForm.headPicUrl : editForm.headPic)" alt="预览" style="max-width: 60px; border-radius: 50%; margin-top: 10px;" />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="submitEdit" class="save-btn">保存</el-button>
        </template>
      </el-dialog>
      <!-- 审核用户对话框 -->
      <el-dialog v-model="auditDialogVisible" title="审核用户" width="400px" class="custom-dialog" :close-on-click-modal="false">
        <el-radio-group v-model="auditStatus">
          <el-radio label="approve">通过</el-radio>
          <el-radio label="reject">拒绝</el-radio>
        </el-radio-group>
        <el-input v-if="auditStatus==='reject'" v-model="auditReason" placeholder="请输入拒绝理由" style="margin-top: 16px;" />
        <template #footer>
          <el-button @click="auditDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="submitAudit" class="save-btn">提交</el-button>
        </template>
      </el-dialog>
      <!-- 添加用户对话框 -->
      <el-dialog v-model="addDialogVisible" title="添加用户" width="400px" class="custom-dialog" :close-on-click-modal="false">
        <el-form :model="addForm" ref="addFormRef" label-width="80px" :rules="rules">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="addForm.phone" />
          </el-form-item>
          <el-form-item label="头像">
            <el-upload
              class="upload-demo"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAddFileChange"
            >
              <el-button type="primary">选择头像</el-button>
            </el-upload>
            <div v-if="addForm.headPicUrl" class="preview-img">
              <img :src="isBase64(addForm.headPicUrl) ? addForm.headPicUrl : getHeadPicUrl(addForm.headPicUrl)" alt="预览" style="max-width: 60px; border-radius: 50%; margin-top: 10px;" />
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="submitAdd" class="save-btn">提交</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  UserFilled, Search, Refresh, Edit, Plus, Download
} from '@element-plus/icons-vue'
import { searchUser, updateUser, banUser, unbanUser, auditUser, deleteUser, addUser } from '@/request/user.js'

const searchForm = reactive({ username: '', phone: '', roleId: '' })
const userList = ref([])
const loading = ref(false)
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = reactive({ id: '', username: '', phone: '', headPic: '', headPicUrl: '', file: null })
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
}
const auditDialogVisible = ref(false)
const auditStatus = ref('approve')
const auditReason = ref('')
const auditUserId = ref('')
// 新增用户相关
const addDialogVisible = ref(false)
const addFormRef = ref()
const addForm = reactive({ username: '', phone: '', headPicUrl: '', file: null })

// 统计数据
const totalUsers = computed(() => userList.value.length)
const activeUsers = computed(() => userList.value.filter(user => user.roleId === 1 || user.roleId === 2).length)
const verifiedUsers = computed(() => userList.value.filter(user => user.roleId === 2).length)
const bannedUsers = computed(() => userList.value.filter(user => user.roleId === -1).length)

const IMAGE_PREFIX = 'http://localhost:2000/image/';
function getHeadPicUrl(url) {
  if (!url) return '';
  if (url.startsWith('http')) return url;
  return IMAGE_PREFIX + url.replace(/^\\|\//, '');
}

function isBase64(str) {
  return /^data:image/.test(str);
}

function fetchList() {
  loading.value = true
  searchUser({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    username: searchForm.username,
    phone: searchForm.phone,
    roleId: searchForm.roleId
  })
    .then(res => {
      userList.value = res.data.records || res.data.records || []
      total.value = res.data.total || 0
    })
    .finally(() => loading.value = false)
}
function handleSearch() {
  pageNum.value = 1
  fetchList()
}
function resetSearch() {
  searchForm.username = ''
  searchForm.phone = ''
  searchForm.roleId = ''
  pageNum.value = 1
  fetchList()
}
function handlePageChange(val) {
  pageNum.value = val
  fetchList()
}
function handleSizeChange(val) {
  pageSize.value = val
  pageNum.value = 1
  fetchList()
}
function editUser(row) {
  editForm.id = row.id
  editForm.username = row.username
  editForm.phone = row.phone
  editForm.headPic = row.headPic
  editForm.headPicUrl = row.headPic
  editDialogVisible.value = true
}
function handleEditFileChange(file) {
  const reader = new FileReader()
  reader.onload = e => {
    editForm.headPicUrl = e.target.result
  }
  reader.readAsDataURL(file.raw)
  editForm.file = file.raw
}
function handleAddFileChange(file) {
  const reader = new FileReader()
  reader.onload = e => {
    addForm.headPicUrl = e.target.result
  }
  reader.readAsDataURL(file.raw)
  addForm.file = file.raw
}
function submitEdit() {
  editFormRef.value.validate(valid => {
    if (!valid) return
    const formData = new FormData()
    formData.append('id', editForm.id)
    formData.append('username', editForm.username)
    formData.append('phone', editForm.phone)
    if (editForm.file) {
      formData.append('headPic', editForm.file)
    }
    updateUser(formData).then(res => {
      if (res.data.success) {
        ElMessage.success('更新成功')
        editDialogVisible.value = false
        fetchList()
      } else {
        ElMessage.error(res.data.message || '更新失败')
      }
    })
  })
}
function banUserHandler(id) {
  banUser(id).then(res => {
    if (res.data.success) {
      ElMessage.success('用户已封禁')
      fetchList()
    } else {
      ElMessage.error(res.data.message || '封禁失败')
    }
  })
}
function unbanUserHandler(id) {
  unbanUser(id).then(res => {
    if (res.data.success) {
      ElMessage.success('用户已解封')
      fetchList()
    } else {
      ElMessage.error(res.data.message || '解封失败')
    }
  })
}
function openAuditDialog(row) {
  auditUserId.value = row.id
  auditStatus.value = 'approve'
  auditReason.value = ''
  auditDialogVisible.value = true
}
function submitAudit() {
  auditUser(auditUserId.value, auditStatus.value, auditReason.value).then(res => {
    if (res.data.success) {
      ElMessage.success('审核完成')
      auditDialogVisible.value = false
      fetchList()
    } else {
      ElMessage.error(res.data.message || '审核失败')
    }
  })
}
function deleteUserHandler(id) {
  deleteUser(id).then(res => {
    if (res.data.success) {
      ElMessage.success('删除成功')
      fetchList()
    } else {
      ElMessage.error(res.data.message || '删除失败')
    }
  })
}
// 新增用户提交
function submitAdd() {
  addFormRef.value.validate(valid => {
    if (!valid) return
    const formData = new FormData()
    formData.append('username', addForm.username)
    formData.append('phone', addForm.phone)
    if (addForm.file) {
      formData.append('headPic', addForm.file)
    }
    addUser(formData).then(res => {
      if (res.data.success) {
        ElMessage.success('添加成功')
        addDialogVisible.value = false
        addForm.username = ''
        addForm.phone = ''
        addForm.headPicUrl = ''
        addForm.file = null
        fetchList()
      } else {
        ElMessage.error(res.data.message || '添加失败')
      }
    })
  })
}

// 简化的方法
function exportUsers() {
  ElMessage.info('导出功能开发中...')
}

function refreshData() {
  fetchList()
  ElMessage.success('数据已刷新')
}

function getRoleTagType(roleId) {
  switch (roleId) {
    case 1: return 'primary'
    case 2: return 'success'
    case 3: return 'danger'
    case 0: return 'warning'
    case -1: return 'danger'
    default: return 'info'
  }
}

function getRoleText(roleId) {
  switch (roleId) {
    case 1: return '普通用户'
    case 2: return '已认证'
    case 3: return '被拒绝'
    case 0: return '待审核'
    case -1: return '封禁'
    default: return '未知'
  }
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.user-manage {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0;
  height: 100%;
  box-sizing: border-box;
}
.box-card {
  border-radius: 0;
  border: none;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: none;
}
.header-section {
  background: #f5f7fa;
  color: #303133;
  padding: 16px 20px;
  margin: 0 0 20px 0;
  border-bottom: 1px solid #e4e7ed;
  flex-shrink: 0;
}
.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.title-section {
  display: flex;
  align-items: center;
  gap: 8px;
}
.title-icon {
  font-size: 20px;
  color: #409eff;
}
.title-text {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}
.add-button {
  background: #409eff;
  border: 1px solid #409eff;
  color: white;
  font-weight: 400;
  padding: 8px 16px;
  border-radius: 4px;
}
.add-button:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}
.search-form {
  background: #fafafa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  border: 1px solid #e4e7ed;
  flex-shrink: 0;
}
.search-input {
  width: 200px;
}
.search-btn, .reset-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 400;
}
.search-btn {
  background: #409eff;
  border: 1px solid #409eff;
  color: white;
}
.reset-btn {
  background: white;
  border: 1px solid #dcdfe6;
  color: #606266;
}
.data-table {
  width: 100%;
  margin: 0 auto;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  flex: 1;
}
.data-table :deep(.el-table) {
  border: none;
  height: 100%;
}
.data-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}
.data-table :deep(.el-table__header th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  border-bottom: 1px solid #e4e7ed;
}
.data-table :deep(.el-table__body td) {
  border-bottom: 1px solid #f0f0f0;
}
.data-table :deep(.el-table__body tr:hover) {
  background-color: #f5f7fa;
}
.action-btn {
  margin: 0 4px;
  padding: 6px 12px;
  border-radius: 4px;
  font-weight: 400;
}
.edit-btn {
  background: #409eff;
  border: 1px solid #409eff;
  color: white;
}
.delete-btn {
  background: #f56c6c;
  border: 1px solid #f56c6c;
  color: white;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 16px 0;
  flex-shrink: 0;
}
.custom-dialog {
  border-radius: 8px;
}
.cancel-btn {
  background: white;
  border: 1px solid #dcdfe6;
  color: #606266;
  padding: 8px 16px;
  border-radius: 4px;
}
.save-btn {
  background: #409eff;
  border: 1px solid #409eff;
  color: white;
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 400;
}
</style>
